#!/usr/bin/env node
var crypto = require('crypto');
//var db_user = require('../db/db_user');
var connect = require('../db/connect');
var connection = connect.connection;

module.exports.showSignup = function(req,res){
    res.render('signup')
}
module.exports.signup = function(req, res){  
    var user = req.body;
    console.log(req.body)
    var username = user.LoginName.trim();
    console.log('username: '+username)
    var pass = user.Password.trim();
    var rPass = user.R_password.trim();
    if(pass === rPass){ // Two password are same.
        connection.query( 'select LoginName from Customer',
            function(err,rows){
                var isUserExisted = false;
                rows.forEach(function(e){    
                if(e.LoginName === username){
                    console.log(username+' Existed');
                    isUserExisted = true;
                }
                });
                if(isUserExisted === false){ //No existed user
                    user.Password = md5(pass);
                    delete user.R_password;
                    user.Account=0;
                    //var q = "INSERT INTO `Customer` (`LoginName`,`Password`,`TrueName`,`Gender`,`Address`,`Postcode`,`Email`,`Phone`,`PswQuestion`,`PswAnswer`,`Account`) VALUES ('C000000001','Abel','lebA','Abel Tang','Male','Rua de Bruxelas edf Jardim Nam Ngon room G101 Macau','00853','dydeong@gmail.com','(00853)66669999','What''s my favority food?','Fish',10000.0);"
                    var s = connection.query(
                        'insert into Customer set ?', user 
                         ,function(error){if(error) throw error;});
                    console.log(s);
                     res.render('signup',{success:'Sign up success.'});
                }else printRepeatInfo(req, res);
            }
                         );
}else res.render('signup', {error: 'Password in two times should be consistent'});
}

module.exports.showSignin = function(req, res){
    res.render('signin');
}
module.exports.signin = function(req, res){
    connection.query(
        'select LoginName from Customer',
        function(err,rows){
            var isUserExisted = false, isPasswordSame = true; //booleans
            console.log('pswd_user:||'+req.body.password+'||');
            var username = req.body.username.trim(),
                password = md5(req.body.password.trim());
            console.log('Ps1_md5: '+password);
            
            rows.forEach(function(e){    
                if(e.LoginName === username){
                    console.log(username+' Existed');
                    isUserExisted = true;
                }
            });
            if(isUserExisted){
                connection.query("select Password from Customer where LoginName = '"+username+"'",
                    function(err,results){
                        var pswd_db= results[0].Password;
                        console.log('pswd_db_db:||'+pswd_db+'||');
                        pswd_db = pswd_db.trim();
                        pswd_db = md5(pswd_db); //After can delete
                        console.log('pw_db_md5: '+pswd_db);
                        if(pswd_db === password){
                            req.session.username = username;
                            console.log('req.session.username: '+req.session.username);
                            res.render('signin', {username: username, success:'Sign in success'});
                        }else res.render('signin', {error: 'Wrong password!'});
                    }            
                                 );
            }else res.render('signin', {error: 'Wrong username, or no this user'});
        });   

}
module.exports.signout = function(req, res){
    var method = req.method.toLowerCase(); 
    req.session = null;  
    res.render('index', {title: 'ISI website', cartNum: 0});
}

function md5(str) {
  var md5sum = crypto.createHash('md5');
  md5sum.update(str);
  str = md5sum.digest('hex');
  return str;
}
function printRepeatInfo(req, res){
     res.render('signup', {error: 'Username existed'})
    //TODO
}

